<template>
  <div class="countdown-container">
    <h2 class="countdown-title">签到倒计时</h2>
    <div class="countdown-timer" v-if="!isEnded">
      <div class="countdown-section">
        <span class="countdown-value">{{ minutes }}</span>
        <span class="countdown-label">分</span>
      </div>
      <div class="countdown-section">
        <span class="countdown-value">{{ seconds }}</span>
        <span class="countdown-label">秒</span>
      </div>
      <div class="countdown-section">
        <span class="countdown-value">{{ milliseconds }}</span>
        <span class="countdown-label">毫秒</span>
      </div>
    </div>

    <div v-if="teacher_role" class="controls">
      <el-select v-model="selectedDuration" placeholder="请选择倒计时时间" v-if="!isStarted">
        <el-option label="5分钟" value="300000"></el-option>
        <el-option label="10分钟" value="600000"></el-option>
        <el-option label="15分钟" value="900000"></el-option>
        <el-option label="30分钟" value="1800000"></el-option>
      </el-select>
      <el-select v-model="work_value" placeholder="请选择专业" v-if="!isStarted">
        <el-option v-for="option in work_options" :key="option.value" :label="option.label"
          :value="option.value"></el-option>
      </el-select>
      <el-button class="buttons" v-if="!isStarted" @click="startCountdown">发布签到</el-button>
      <el-button class="buttons" v-if="isStarted" @click="cancelCountdown">取消签到</el-button>
    </div>
    <el-button class="buttons" v-if="student_role">签到</el-button>
  </div>
</template>

<script>
import { pubSignIn } from '@/utils/urlManager';
import axios from 'axios';

export default {
  name: 'Countdown',
  data() {
    return {
      totalMilliseconds: 0, // 总倒计时时间（毫秒）
      intervalId: null,
      isStarted: false,
      isEnded: false,
      minutes: 0,
      seconds: 0,
      milliseconds: 0,
      selectedDuration: '300000', // 默认选中的倒计时时间
      deadline: null, // 截止时间
      student_role: false,
      teacher_role: false,
      work_options: [
        { value: 'homework_001', label: '软件工程' },
        { value: 'homework_002', label: '计算机程序设计' },
        { value: 'homework_003', label: '数据结构与算法' },
        { value: 'homework_004', label: '操作系统' },
        { value: 'homework_005', label: 'MySQL数据库' },
        { value: 'homework_006', label: 'HTML基础' },
        { value: 'homework_007', label: '编译原理' },
        { value: 'homework_008', label: 'Java基础' },
        { value: 'homework_009', label: '软件测试' },
        { value: 'homework_010', label: 'C语言基础' }
      ],
      work_value: '' // 选中的专业
    };
  },
  methods: {
    updateCountdown() {
      const now = new Date().getTime();
      const timeLeft = this.deadline - now;

      if (timeLeft <= 0) {
        clearInterval(this.intervalId);
        this.isEnded = true;
        this.isStarted = false; // 倒计时结束后，将 isStarted 设置为 false
        this.showEndMessage(); // 显示结束提示
        this.saveState(); // 保存状态
        return;
      }

      this.minutes = Math.floor(timeLeft / (60 * 1000));
      this.seconds = Math.floor((timeLeft % (60 * 1000)) / 1000);
      this.milliseconds = Math.floor((timeLeft % 1000) / 10); // 显示10毫秒为单位
      this.saveState(); // 保存状态
    },
    startCountdown() {
      if (!this.work_value) {
        this.$alert('请选择专业', '提示', {
          confirmButtonText: '确定',
          type: 'warning'
        });
        return;
      }
      axios.put(pubSignIn, {
        "subjectId": "wenhua_001",
        "endline": "2025-04-24T14:30:00"
      })
        .then((response) => {
          if (response.data.data != null) {
            this.$message.success("签到发布成功！！");
            const now = new Date().getTime();
            this.deadline = now + parseInt(this.selectedDuration, 10);
            this.isStarted = true;
            this.isEnded = false;
            this.intervalId = setInterval(this.updateCountdown, 10); // 每10毫秒更新一次
            this.updateCountdown(); // 立即更新一次
            this.saveState(); // 保存状态
          }else{
            this.$message.warning(response.data.msg);
          }
        })
        .catch((err)=>{
          this.$message.error(err)
          console.log(err);
        })


    },
    cancelCountdown() {
      clearInterval(this.intervalId);
      this.isStarted = false;
      this.isEnded = true;
      this.saveState(); // 保存状态
      this.$alert('签到已取消', '取消提示', {
        confirmButtonText: '确定',
        type: 'info',
      });
    },
    showEndMessage() {
      this.$message.success("签到结束啦~~")
    },
    saveState() {
      // 保存倒计时状态到localStorage
      localStorage.setItem('deadline', this.deadline);
      localStorage.setItem('isEnded', this.isEnded);
      localStorage.setItem('isStarted', this.isStarted);
      localStorage.setItem('work_value', this.work_value); // 保存选中的专业
    },
    loadState() {
      // 从localStorage加载倒计时状态
      const savedDeadline = localStorage.getItem('deadline');
      const savedIsEnded = localStorage.getItem('isEnded');
      const savedIsStarted = localStorage.getItem('isStarted');
      const savedWorkValue = localStorage.getItem('work_value');

      if (savedDeadline) {
        this.deadline = parseInt(savedDeadline, 10);
        this.isEnded = savedIsEnded === 'true';
        this.isStarted = savedIsStarted === 'true';
        this.work_value = savedWorkValue; // 加载选中的专业
        if (!this.isEnded && this.isStarted) {
          this.updateCountdown();
          this.intervalId = setInterval(this.updateCountdown, 10); // 恢复倒计时
        }
      }
    }
  },
  mounted() {
    this.loadState(); // 加载保存的状态
    if (localStorage.getItem("role") == "1") {
      this.student_role = true;
    } else if (localStorage.getItem("role") == "2") {
      this.teacher_role = true;
    }
  },
  beforeDestroy() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
    this.saveState(); // 保存状态
  },
};
</script>

<style scoped>
.countdown-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f0f0f0;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  margin: 0 auto;
}

.countdown-title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
}

.countdown-timer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.countdown-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 10px;
}

.countdown-value {
  font-size: 70px;
  font-weight: bold;
  color: #4caf50;
  margin-bottom: 5px;
  transition: color 0.3s ease;
}

.countdown-label {
  font-size: 24px;
  color: #666;
  width: 20vw;
}

.controls {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.start-button {
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
  padding: 10px 20px;
  font-size: 16px;
  cursor: pointer;
  margin-top: 10px;
}

.start-button:hover {
  background-color: #45a049;
}
</style>